<template>
  <searchArea :fieldlist="searchList" @search="search" @reset="search" />
  <q-table
    :grid="$q.screen.xs"
    :rows="data"
    :columns="columns"
    row-key="id"
    v-model:pagination="pagination"
    :loading="loading"
    :filter="filter"
    :rows-per-page-options="[25, 50, 100, 0]"
    @request="onRequest"
    binary-state-sort
    :visible-columns="visibleColumns"
    :style="$q.screen.xs ? '' : 'max-height: calc(100vh - 100px)'"
    class="my-sticky-virtscroll-table"

  >
    <template v-slot:top>
      <div class="q-table__title q-mr-md">{{ modelLabel }}</div>
      <q-select
        label="选择显示列"
        v-model="visibleColumns"
        multiple
        borderless
        dense
        options-dense
        :display-value="visibleColumns.length + '/' + columns.length + '列'"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        :style="{'min-width': $q.screen.xs ? '100px' : '150px'}"
      />
      <q-space />
      <q-btn label="导出Excel" color="primary" icon="cloud_download" @click="exportToExcel()">
        <q-tooltip>导出Excel</q-tooltip>
      </q-btn>
    </template>

    <template v-slot:bottom-row="props" v-if="summary">
      <q-tr class="bg-yellow-2 text-center text-bold">
        <q-td :key="col.name" v-for="(col, idx) in props.cols">
          <div v-if="idx === 0">本页汇总</div>
          <div v-else-if="summary.page[col.field] !== undefined" class="text-bold text-center">
            <div v-if="moneyFields.includes(col.field)">{{ isNumber(summary.page[col.field]) ? Number(summary.page[col.field]).toFixed(2) : summary.page[col.field] }} 元</div>
            <div v-else>{{ summary.page[col.field] }}</div>
          </div>
        </q-td>
      </q-tr>
      <q-tr class="bg-yellow-4 text-center text-bold bottom-row">
        <q-td :key="col.name" v-for="(col, idx) in props.cols">
          <div v-if="idx === 0">全部汇总</div>
          <div v-else-if="summary.total[col.field] !== undefined" class="text-bold text-center">
            <div v-if="moneyFields.includes(col.field)">{{ isNumber(summary.total[col.field]) ? Number(summary.total[col.field]).toFixed(2) : summary.total[col.field] }} 元</div>
            <div v-else>{{ summary.total[col.field] }}</div>
          </div>
        </q-td>
      </q-tr>
    </template>

    <template v-slot:item="props">
      <q-list dense class="fit shadow-1 q-mb-md q-py-md">
        <q-item v-for="col in props.cols" :key="col.name">
          <q-item-section class="text-grey-8">
            <q-item-label>{{ col.label }}</q-item-label>
          </q-item-section>
          <q-item-section>
            <q-item-label>{{ col.value }}</q-item-label>
          </q-item-section>
        </q-item>
      </q-list>

      <q-list dense class="fit shadow-1 q-mb-md q-py-md bg-yellow-2" v-if="data.length > 0 && props.rowIndex === data.length - 1">
        <q-item class="bg-yellow-2">
          <q-item-section>
            <q-item-label class="text-bold">本页汇总</q-item-label>
          </q-item-section>
        </q-item>
        <q-item class="bg-yellow-2" v-for="[key, value] of Object.entries(summary.page).filter(([k, v]) => props.colsMap[k])" :key="key">
          <q-item-section class="text-grey-8">
            <q-item-label>{{ props.colsMap[key].label }}</q-item-label>
          </q-item-section>
          <q-item-section>
            <q-item-label class="text-bold">
              <div v-if="moneyFields.includes(key)">
                <div v-if="typeof value === 'object'">
                  <div v-for="(val, k) in value" :key="k">
                    {{ val.currency_cn }}: {{ isNumber(val.value) ? Number(val.value).toFixed(2) : val.value }}
                  </div>
                </div>
                <div v-else>{{ isNumber(value) ? Number(value).toFixed(2) : value }}</div>
              </div>
              <div v-else>{{ value }}</div>
            </q-item-label>
          </q-item-section>
        </q-item>

        <q-item class="bg-yellow-4">
          <q-item-section>
            <q-item-label class="text-bold">全部汇总</q-item-label>
          </q-item-section>
        </q-item>
        <q-item class="bg-yellow-4" v-for="[key, value] of Object.entries(summary.total).filter(([k, v]) => props.colsMap[k])" :key="key">
          <q-item-section class="text-grey-8">
            <q-item-label>{{ props.colsMap[key].label }}</q-item-label>
          </q-item-section>
          <q-item-section>
            <q-item-label class="text-bold">
              <div v-if="moneyFields.includes(key)">
                <div v-if="typeof value === 'object'">
                  <div v-for="(val, k) in value" :key="k">
                    {{ val.currency_cn }}: {{ isNumber(val.value) ? Number(val.value).toFixed(2) : val.value }}
                  </div>
                </div>
                <div v-else>{{ isNumber(value) ? Number(value).toFixed(2) : value }}</div>
              </div>
              <div v-else>{{ value }}</div>
            </q-item-label>
          </q-item-section>
        </q-item>
      </q-list>
    </template>
  </q-table>
</template>

<script>
import { defineComponent } from 'vue';
import searchArea from 'src/components/SearchArea.vue';
import { listPageMix } from 'src/lib/mixin.js';
import pageConfig from 'app/search/tenant/device/summary.js';
import doExport from 'src/lib/exportToExcel.js';
import { isNumber } from 'src/lib/utils.js';
import { useMeta } from 'quasar';
import { useStore } from 'stores/store';

export default defineComponent({
  name: 'deviceSummary',
  setup (props, context) {
    const $store = useStore();
    const modelLabel = '设备档案';
    const moduleName = 'device';
    const submoduleName = 'summary';
    const listApi = `/c2/tenant/${moduleName}/summary`; // 数据列表接口

    useMeta({
      // 设置文件标题
      title: `${modelLabel} - ${$store.siteConfig.appName} - 木多鱼系列`
    });

    return {
      modelLabel,
      moduleName,
      submoduleName,
      listApi
    }
  },
  components: {
    searchArea
  },
  mixins: [listPageMix],
  data () {
    return {
      summary: { total: {}, page: {} }, // 统计数据
      columns: [
        { name: 'year', label: '年', field: 'year', sortable: true, align: 'center' },
        { name: 'month', label: '月', field: 'month', sortable: true, align: 'center' },
        { name: 'day', label: '日', field: 'day', sortable: true, align: 'center' },
        { name: 'create_user_name', label: '创建人', field: 'create_user_name', sortable: true, align: 'center' },
        { name: 'customer_name', label: '所属客户', field: 'customer_name', sortable: true, align: 'center' },
        { name: 'bill_count', label: '设备数量', field: 'bill_count', sortable: true, align: 'center' }
      ],
      visibleColumns: ['customer_name', 'bill_count'],
      moneyFields: []
    }
  },
  created () {
    this.assembly(pageConfig.search); // 根据配置生成搜索条件
    this.pagination.sortBy = 'sale_count';
  },
  mounted () {
    /* if (['', 'id'].includes(this.pagination.sortBy)) {
      if (this.visibleColumns.indexOf('year') > 0) {
        this.pagination.sortBy = 'year';
      } else if (this.visibleColumns.indexOf('month') > 0) {
        this.pagination.sortBy = 'month';
      } else if (this.visibleColumns.indexOf('day') > 0) {
        this.pagination.sortBy = 'day';
      }
    } */
  },
  methods: {
    exportToExcel () {
      const { sortBy, descending } = this.pagination;
      this.$axios.post(this.listApi, { filter: this.filter, sortBy, descending, columns: this.visibleColumns }).then(({ data }) => {
        const aoa = [];

        const visibleColumns = this.columns.filter(col => this.visibleColumns.includes(col.name)); // 可见列
        // 表头
        aoa.push(visibleColumns.map(col => col.label));

        // 数据
        for (const row of data.data) {
          aoa.push(visibleColumns.map(col => {
            let value;
            if (col.format) {
              value = col.format(row[col.field], row);
            } else {
              value = row[col.field];
            }
            return isNaN(value) ? value : Number(value);
          }));
        }

        // 全部汇总
        aoa.push(visibleColumns.map((col, idx) => {
          if (idx === 0) {
            return '汇总'
          } else if (data.summary.total[col.field] !== undefined) {
            return data.summary.total[col.field];
          } else {
            return '';
          }
        }));

        doExport(aoa, `${this.modelLabel}.xlsx`);
      });
    },
    isNumber (val) {
      return isNumber(val);
    }
  },
  watch: {
    visibleColumns () {
      this.search();
    }
  }
});
</script>
